<template>
  <div class="user-manage">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="searchForm.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择">
          <el-option label="启用" value="1"/>
          <el-option label="禁用" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="fetchUsers">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增按钮 -->
    <el-button icon="Plus" style="margin-bottom: 10px;" type="primary" @click="openAddDialog">新增用户</el-button>

    <!-- 用户表格 -->
    <el-table :data="userList" border style="width: 100%">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="用户编号" prop="id" width="100"/>
      <el-table-column label="用户头像" prop="avatar">
        <template #default="scope">
          <el-avatar :src="scope.row.avatar"/>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="username"/>
      <el-table-column label="手机号" prop="phone"/>
      <el-table-column label="邮箱" prop="email"/>
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0" @change="updateStatus(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180"/>
      <el-table-column label="修改时间" prop="updateTime" width="180"/>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button icon="Edit" type="text" @click="openEditDialog(scope.row)">修改</el-button>
          <el-button icon="Delete" type="text" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 15, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentPageChange"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"/>
        </el-form-item>
        <el-form-item v-if="isAdd" label="密码" prop="password">
          <el-input v-model="form.password" type="password"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"/>
        </el-form-item>
        <!--        <el-form-item label="状态" prop="status">-->
        <!--          <el-switch v-model="form.status" active-value="1" inactive-value="0" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {onMounted, reactive, ref} from 'vue'


export default {


  setup() {
    // 搜索表单（双向绑定）
    const searchForm = reactive({
      username: '',
      phone: ''
      // status: ''
    })


    // 表格数据 + 分页
    const userList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(15)
    const total = ref(66) // 模拟总条数

    // 弹窗相关（新增/编辑）
    const dialogVisible = ref(false)
    const isAdd = ref(true)
    const dialogTitle = ref('新增用户')
    const form = reactive({
      username: '',
      password: '',
      phone: '',
      email: ''
      // status: '1' // 默认为“启用”
    })

    // 模拟“获取用户列表”请求
    const fetchUsers = () => {
      // 实际开发中替换为接口请求，这里用模拟数据
      userList.value = Array.from({length: pageSize.value}, (_, i) => ({
        id: 100 + i,
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 模拟头像
        username: `test_user_${i}`,
        phone: `13${Math.floor(Math.random() * 100000000)}`, // 模拟手机号
        email: `vibe_music_${i}@163.com`, // 模拟邮箱
        status: i % 2 === 0 ? '1' : '0', // 奇偶行模拟“启用/禁用”
        createTime: '2025-03-07 18:06:24',
        updateTime: '2025-04-02 16:45:43'
      }))
    }


    // 模拟“获取用户列表”请求
    // const fetchUsers = async () => {
    //   try {
    //     // 实际开发中替换为接口请求，这里用模拟数据
    //     const response = await axios.get('http://localhost:8081/admin/user/getUserList', {
    //       params: {
    //         page: 1, // 当前页码
    //         pageSize: pageSize.value, // 每页大小
    //         username:'',
    //         phone:''
    //       }
    //     });
    //     userList.value = response.data.data.records;
    //   } catch (error) {
    //     console.error('获取用户列表失败:', error);
    //   }
    // };

// 在组件挂载时调用 fetchUsers 函数
    onMounted(() => {
      fetchUsers();
    });


    // 重置搜索条件
    const resetSearch = () => {
      searchForm.username = ''
      searchForm.phone = ''
      searchForm.status = ''
      fetchUsers()
    }

    // 分页事件
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchUsers()
    }
    const handleCurrentPageChange = (val) => {
      currentPage.value = val
      fetchUsers()
    }

    // 打开“新增/编辑”弹窗
    const openAddDialog = () => {
      isAdd.value = true
      dialogTitle.value = '新增用户'
      form.username = ''
      form.password = ''
      form.phone = ''
      form.email = ''
      form.status = '1'
      dialogVisible.value = true
    }
    const openEditDialog = (row) => {
      isAdd.value = false
      dialogTitle.value = '编辑用户'
      form.username = row.username
      form.phone = row.phone
      form.email = row.email
      form.status = row.status
      dialogVisible.value = true
    }

    // 保存用户（新增/编辑）
    const saveUser = () => {
      console.log('提交的用户数据：', form)
      dialogVisible.value = false
      fetchUsers() // 保存后刷新列表
    }

    // 更新用户状态（开关触发）
    const updateStatus = (row) => {
      console.log('更新用户状态：', row.id, row.status)
    }

    // 删除用户
    const deleteUser = (id) => {
      console.log('删除用户ID：', id)
      fetchUsers() // 删除后刷新列表
    }

    // 初始化加载用户列表
    fetchUsers()

    return {
      searchForm,
      userList,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      isAdd,
      dialogTitle,
      form,
      fetchUsers,
      resetSearch,
      handleSizeChange,
      handleCurrentPageChange,
      openAddDialog,
      openEditDialog,
      saveUser,
      updateStatus,
      deleteUser
    }
  }
}
</script>

<style scoped>
.user-manage {
  width: 100%;
}

.search-form {
  margin-bottom: 10px;
}
</style>